package com.ty.game.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

/**
 * @author: Troy.Chen(失足程序员, 15388152619)
 * @version: 2021-08-06 09:45
 **/
@Slf4j
@RestController
@RequestMapping("gm/upload")
public class UpLoadFileController implements Serializable {

    private static final long serialVersionUID = 1L;

    public void classFile() {
    }

    @GetMapping("upload")
    public String upload() {
        return "upload";
    }

    @ResponseBody
    @PostMapping("hotfile")
    public String uploadBody(HttpServletRequest request) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        final Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
        while (fileNames.hasNext()) {
            /*html 控件名字*/
            String fileInputName = fileNames.next();
            /*获取控件选择的文件*/
            final List<MultipartFile> files = multipartHttpServletRequest.getFiles(fileInputName);
            for (MultipartFile file : files) {
                saveFile(stringBuilder, request, file);
            }
        }
        return stringBuilder.toString();
    }

    public boolean saveFile(StringBuilder stringBuilder, HttpServletRequest request, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        try {
            String filePath = System.getProperty("user.dir") + "target/temp/";
            File dest = new File(filePath + fileName);
            dest.getParentFile().mkdirs();
            dest.createNewFile();
            file.transferTo(dest);

            try {
                final String parameter = request.getParameter(fileName);
                if (parameter != null) {
                    final long parseLong = Long.parseLong(parameter);
                    dest.setLastModified(parseLong);
                }
            } catch (Exception e) {

            }
            log.info("上传成功：" + dest.getCanonicalPath());
            stringBuilder.append("上传成功：" + fileName).append("\n");
            return true;
        } catch (IOException e) {
            log.error(e.toString(), e);
            stringBuilder.append("上传失败：" + fileName + e.getMessage());
            return false;
        }
    }

}
